package Network;




import General.Globals;
import MetricsRetriever.RetrievalManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Manuel
 */
public class Scheduler {

    private ArrayList<Thread> projectCrawlerThreads;
    private Connector c;
    private Packager p;


    public void startClient(String[] args){
        if(args.length < 1)
        {
            System.out.println("Please insert the server url as parameter!");
            System.exit(0);
        }

        projectCrawlerThreads = new ArrayList<Thread>();
        c = new Connector(args[0]);
        p = new Packager(c);

        //this.requestLink();//TODO change, just for test purposes
        if(args.length == 3){
            this.silentStart(args[1],args[2]);

        }
        else{
            this.showMainMenu();}
        



    }

    private void showMainMenu() {
        try {
            Thread.sleep(750);
        } catch (InterruptedException ex) {
            Logger.getLogger(Scheduler.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Please select what you want to do.\n[1] Request links to process\n[2] Command the crawler to gather new links.\n[3] Exit \n[4] Crawl specified project.");
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        try {
            String line = input.readLine();
            if(line.equals("1"))
                requestLink();
            else if(line.equals("2"))
                requestCrawl();
            else if(line.equals("3"))
                System.exit(0);

           
            else
                this.showMainMenu();

        } catch (IOException ex) {
        }
    }

    private void requestLink() {
       System.out.println("Please insert the number of links to process or return to the main menu with R.");

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        try {
            String line = input.readLine();
            if(line.equals("R"))
                this.showMainMenu();

                String[] args = line.split(",");
                if(args.length < 1){
                    this.requestLink();
                }

                String  response = null;
                for(int i = 0;i<Integer.parseInt(args[0]);i++){
                    System.out.println("Sending out request...");
                    try{
                        response = c.sendPostRequest("0");
                        System.out.println(response);
                        ArrayList<String> l = new ArrayList<String>();
                        l.add(response);
                        //l.add("1;abc;http://code.google.com/p/wiquery/;2100");
                        RetrievalManager rm = new RetrievalManager(l, p,c);
                      //  RetrievalManager rm = new RetrievalManager("https://savior.svn.sourceforge.net/svnroot/savior", "random",0,p,c);
                        rm.start();
                        projectCrawlerThreads.add(rm);
                    }catch(IOException e){
                        e.printStackTrace();
                        System.out.println("Returned bad answer. ");
                    }
                    
                }


        } catch (IOException ex) {
        }
        this.waitForThreads();
    }

    private void requestCrawl() {System.out.println("Please insert the password and the crawl limit separated by comma, return to the main menu with R.");

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        try {
            String line = input.readLine();
            if(line.equals("R"))
                this.showMainMenu();
            if(line.contains(",")){
                String[] args = line.split(",");
                if(args.length < 2){
                    this.requestCrawl();
                }

                String  response = null;
                    System.out.println("Sending out request...");
                    response = c.sendPostRequest("4;"+args[0]+";"+args[1]);
                    String[] arr = response.split(";");
                    if(arr != null && arr.length>1 && arr[0].equals("5")){
                        System.out.println("Received valid response: \""+response+"\"!");
                    }
                }



            else
                this.requestLink();

        } catch (IOException ex) {
        }
    }

    private void silentStart(String ch, String no){
        int number = Integer.parseInt(no);
        String response ="No Response...";

        if(ch.toLowerCase().equals("c")){
            try{
                response = c.sendPostRequest("4;"+Globals.PASSWORD+";"+Integer.toString(number));
            }catch(IOException e){
                
            }
        }
        else if(ch.toLowerCase().equals("p"))
            this.startProcessing(number);

    }

    private void startProcessing(int number) {
        ArrayList<String> links = new ArrayList<String>();
        for(int i = 0;i<number;i++){
            System.out.println("Sending out request...");
            try{
                    String response = c.sendPostRequest("0");
                    System.out.println("received: "+response);
                    links.add(response);}
               catch(IOException ex){
                   
               }
         }
        int part = (int) Math.ceil(links.size()/Globals.threadNumber);
        if(links.size()>Globals.threadNumber){
            for(int j = 0;j<Globals.threadNumber;j++){
                        ArrayList<String> l = new ArrayList<String>();
                        for(int k = 0;k<part;k++){
                            if(links.size()>0){
                                l.add(links.get(0));
                                links.remove(0);
                            }
                        }
                            RetrievalManager rm = new RetrievalManager(l,p,c);
                            rm.start();
                            projectCrawlerThreads.add(rm);

            }
        }
        else{
            for(int j = 0;j<links.size();j++){
                ArrayList<String> l = new ArrayList<String>();
                l.add(links.get(j));
                RetrievalManager rm = new RetrievalManager(l,p,c);
                System.out.println("Starting new thread");
                            rm.start();
                            projectCrawlerThreads.add(rm);

            }
        }
        this.waitForThreads();
    }

    private void waitForThreads() {
        for(int i = 0;i<this.projectCrawlerThreads.size();i++){
            try {
                this.projectCrawlerThreads.get(i).join();
            } catch (InterruptedException ex) {
                System.out.println("Crawler Thread "+ i + " crashed");
            }
        }
    }
}
